from CvPythonExtensions import *
from WriterUtils import *

import CvScreenEnums
import CvUtil
import CvConfigParser
import CvPath
import os
import os.path
import Popup as PyPopup
import shutil 

# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
localText = CyTranslator()

# Change this to change the location where the resulting CIV4ImprovementInfos.xml file 
# will be saved. So if the default value is left to "Test" then the 
# CIV4ImprovementInfos.xml file would be written in a directory called "Test" inside 
# of the Tech Tree Editor mod folder.
# Default value is Test
g_strSaveDirectoryLocation = "Test"

# Change the value to false if the assets directory structure shouldn't be 
# created at the directory specified by the "Save Directory Location".
# Default value is True
g_bCreateAssetHierarchy = True

# Change the value to false if the changes made shouldn't be saved into the 
# assets directory for the tech editor. Changing it to false will require 
# manual copying of the saved files from the directory specified in the 
# "Save Directory Location" configurable option to the editor's asset directory 
# when wanting to edit existing mod files.
# Default value is True
g_bSaveChangesInEditorAssetsDirectory = True

def loadConfigurationValues():
	global g_strSaveDirectoryLocation
	global g_bCreateAssetHierarchy
	global g_bSaveChangesInEditorAssetsDirectory
	
	config = CvConfigParser.CvConfigParser("ViSa_v3.ini")

	if(config != None):
		g_strSaveDirectoryLocation = config.get("Tech Tree Editor", "Save Directory Location", "Test")
		g_bCreateAssetHierarchy = config.getboolean("Tech Tree Editor", "Create Asset Hierarchy", True)
		g_bSaveChangesInEditorAssetsDirectory = config.getboolean("Tech Tree Editor", "Save Changes In Editor Assets Directory", True)

		if(len(g_strSaveDirectoryLocation) == 0):
			g_strSaveDirectoryLocation = "Test"
			
class ImprovementInfoWriter:
		
	def __init__(self):
		loadConfigurationValues()

	def isPrereqNatureYieldsDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getPrereqNatureYield(iI) != 0):
				return true
		return false

	def isYieldChangesDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getYieldChange(iI) != 0):
				return true
		return false

	def isRiverSideYieldChangeDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getRiverSideYieldChange(iI) != 0):
				return true
		return false

	def isHillsYieldChangeDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getHillsYieldChange(iI) != 0):
				return true
		return false

	def isIrrigatedYieldChangeDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getIrrigatedYieldChange(iI) != 0):
				return true
		return false
		
	def isTerrainMakesValidsDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(gc.getNumTerrainInfos()):
			if(objImprovementInfo.getTerrainMakesValid(iI)):
				return true
		return false
		
	def isFeatureMakesValidsDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(gc.getNumFeatureInfos()):
			if(objImprovementInfo.getFeatureMakesValid(iI)):
				return true
		return false

	def isBonusTypeStructsDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(gc.getNumBonusInfos()):
			if(objImprovementInfo.isImprovementBonusMakesValid(iI)):
				return true
		return false

	def isTechYieldChangesDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)
		for iI in range(gc.getNumTechInfos()):
			for iJ in range(YieldTypes.NUM_YIELD_TYPES):
				if(objImprovementInfo.getTechYieldChanges(iI, iJ) != 0):
					return true
		return false

	def isTechYieldChangeDefined(self, iImprovement, iTech):		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getTechYieldChanges(iTech, iI) != 0):
				return true
		return false


	def isRouteYieldChangesDefined(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)
		for iI in range(gc.getNumRouteInfos()):
			for iJ in range(YieldTypes.NUM_YIELD_TYPES):
				if(objImprovementInfo.getRouteYieldChanges(iI, iJ) != 0):
					return true
		return false

	def isRouteYieldChangeDefined(self, iImprovement, iRoute):		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		for iI in range(YieldTypes.NUM_YIELD_TYPES):
			if(objImprovementInfo.getRouteYieldChanges(iRoute, iI) != 0):
				return true
		return false
		
	def printImprovement(self, iImprovement):
		
		objImprovementInfo = gc.getImprovementInfo(iImprovement)

		szText = ""
		
		szText = appendString(szText,"		<ImprovementInfo>")
		
		szText = appendString(szText,"			<Type>%s</Type>" %(objImprovementInfo.getType()))
		szText = appendString(szText,"			<Description>%s</Description>" %(objImprovementInfo.getTextKey()))
		szText = appendString(szText,"			<Civilopedia>%s</Civilopedia>" %(objImprovementInfo.getCivilopediaKey()))

		szText = appendString(szText,"			<ArtDefineTag>%s</ArtDefineTag>" %(objImprovementInfo.getArtDefineTag()))
			
		if(self.isPrereqNatureYieldsDefined(iImprovement)):
			szText = appendString(szText,"			<PrereqNatureYields>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYield>%s</iYield>" %(objImprovementInfo.getPrereqNatureYield(iI)))
			szText = appendString(szText,"			</PrereqNatureYields>")
#		else:
#			szText = appendString(szText,"			<Yields/>")

		if(self.isYieldChangesDefined(iImprovement)):
			szText = appendString(szText,"			<YieldChanges>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYieldChange>%s</iYieldChange>" %(objImprovementInfo.getYieldChange(iI)))
			szText = appendString(szText,"			</YieldChanges>")
#		else:
#			szText = appendString(szText,"			<YieldChanges/>")

		if(self.isRiverSideYieldChangeDefined(iImprovement)):
			szText = appendString(szText,"			<RiverSideYieldChange>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYield>%s</iYield>" %(objImprovementInfo.getRiverSideYieldChange(iI)))
			szText = appendString(szText,"			</RiverSideYieldChange>")
#		else:
#			szText = appendString(szText,"			<RiverSideYieldChange/>")

		if(self.isHillsYieldChangeDefined(iImprovement)):
			szText = appendString(szText,"			<HillsYieldChange>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYield>%s</iYield>" %(objImprovementInfo.getHillsYieldChange(iI)))
			szText = appendString(szText,"			</HillsYieldChange>")
#		else:
#			szText = appendString(szText,"			<HillsYieldChange/>")

		if(self.isIrrigatedYieldChangeDefined(iImprovement)):
			szText = appendString(szText,"			<IrrigatedYieldChange>")
			for iI in range(YieldTypes.NUM_YIELD_TYPES):
				szText = appendString(szText,"				<iYield>%s</iYield>" %(objImprovementInfo.getIrrigatedYieldChange(iI)))
			szText = appendString(szText,"			</IrrigatedYieldChange>")
#		else:
#			szText = appendString(szText,"			<IrrigatedYieldChange/>")
			
		szText = appendString(szText,"			<bActsAsCity>%s</bActsAsCity>" %(boolToInt(objImprovementInfo.isActsAsCity())))
		szText = appendString(szText,"			<bHillsMakesValid>%s</bHillsMakesValid>" %(boolToInt(objImprovementInfo.isHillsMakesValid())))
		szText = appendString(szText,"			<bFreshWaterMakesValid>%s</bFreshWaterMakesValid>" %(boolToInt(objImprovementInfo.isFreshWaterMakesValid())))
		szText = appendString(szText,"			<bRiverSideMakesValid>%s</bRiverSideMakesValid>" %(boolToInt(objImprovementInfo.isRiverSideMakesValid())))
		szText = appendString(szText,"			<bNoFreshWater>%s</bNoFreshWater>" %(boolToInt(objImprovementInfo.isNoFreshWater())))
		szText = appendString(szText,"			<bRequiresFlatlands>%s</bRequiresFlatlands>" %(boolToInt(objImprovementInfo.isRequiresFlatlands())))
		szText = appendString(szText,"			<bRequiresRiverSide>%s</bRequiresRiverSide>" %(boolToInt(objImprovementInfo.isRequiresRiverSide())))
		szText = appendString(szText,"			<bRequiresIrrigation>%s</bRequiresIrrigation>" %(boolToInt(objImprovementInfo.isRequiresIrrigation())))
		szText = appendString(szText,"			<bCarriesIrrigation>%s</bCarriesIrrigation>" %(boolToInt(objImprovementInfo.isCarriesIrrigation())))
		szText = appendString(szText,"			<bRequiresFeature>%s</bRequiresFeature>" %(boolToInt(objImprovementInfo.isRequiresFeature())))
		szText = appendString(szText,"			<bWater>%s</bWater>" %(boolToInt(objImprovementInfo.isWater())))
		szText = appendString(szText,"			<bGoody>%s</bGoody>" %(boolToInt(objImprovementInfo.isGoody())))
		szText = appendString(szText,"			<bPermanent>%s</bPermanent>" %(boolToInt(objImprovementInfo.isPermanent())))

		if(objImprovementInfo.useLSystem()):
			szText = appendString(szText,"			<bUseLSystem>%s</bUseLSystem>" %(boolToInt(objImprovementInfo.useLSystem())))

		szText = appendString(szText,"			<iTilesPerGoody>%s</iTilesPerGoody>" %(objImprovementInfo.getTilesPerGoody()))
		szText = appendString(szText,"			<iGoodyRange>%s</iGoodyRange>" %(objImprovementInfo.getGoodyUniqueRange()))
		szText = appendString(szText,"			<iUpgradeTime>%s</iUpgradeTime>" %(objImprovementInfo.getUpgradeTime()))
		szText = appendString(szText,"			<iAirBombDefense>%s</iAirBombDefense>" %(objImprovementInfo.getAirBombDefense()))
		szText = appendString(szText,"			<iDefenseModifier>%s</iDefenseModifier>" %(objImprovementInfo.getDefenseModifier()))
		szText = appendString(szText,"			<iPillageGold>%s</iPillageGold>" %(objImprovementInfo.getPillageGold()))				

		if(self.isTerrainMakesValidsDefined(iImprovement)):
			szText = appendString(szText,"			<TerrainMakesValids>")
			for iI in range(gc.getNumTerrainInfos()):
				if(objImprovementInfo.getTerrainMakesValid(iI)):
					szText = appendString(szText,"			<TerrainMakesValid>")
					szText = appendString(szText,"				<TerrainType>%s</TerrainType>" %(gc.getTerrainInfo(iI).getType()))
					szText = appendString(szText,"				<bMakesValid>%s</bMakesValid>" %(boolToInt(objImprovementInfo.getTerrainMakesValid(iI))))
					szText = appendString(szText,"			</TerrainMakesValid>")
			szText = appendString(szText,"			</TerrainMakesValids>")
		else:
			szText = appendString(szText,"			<TerrainMakesValids/>")

		if(self.isFeatureMakesValidsDefined(iImprovement)):
			szText = appendString(szText,"			<FeatureMakesValids>")
			for iI in range(gc.getNumFeatureInfos()):
				if(objImprovementInfo.getFeatureMakesValid(iI)):
					szText = appendString(szText,"			<FeatureMakesValid>")
					szText = appendString(szText,"				<FeatureType>%s</FeatureType>" %(gc.getFeatureInfo(iI).getType()))
					szText = appendString(szText,"				<bMakesValid>%s</bMakesValid>" %(boolToInt(objImprovementInfo.getFeatureMakesValid(iI))))
					szText = appendString(szText,"			</FeatureMakesValid>")
			szText = appendString(szText,"			</FeatureMakesValids>")
		else:
			szText = appendString(szText,"			<FeatureMakesValids/>")
		
		if(self.isBonusTypeStructsDefined(iImprovement)):
			szText = appendString(szText,"			<BonusTypeStructs>")
			for iI in range(gc.getNumBonusInfos()):
				if(objImprovementInfo.isImprovementBonusMakesValid(iI)):
					szText = appendString(szText,"				<BonusTypeStruct>")
					szText = appendString(szText,"					<BonusType>%s</BonusType>" %(gc.getBonusInfo(iI).getType()))
					szText = appendString(szText,"					<bBonusMakesValid>%s</bBonusMakesValid>" %(boolToInt(objImprovementInfo.isImprovementBonusMakesValid(iI))))
					szText = appendString(szText,"					<bBonusTrade>%s</bBonusTrade>" %(boolToInt(objImprovementInfo.isImprovementBonusTrade(iI))))
					szText = appendString(szText,"					<iDiscoverRand>%s</iDiscoverRand>" %(objImprovementInfo.getImprovementBonusDiscoverRand(iI)))
					szText = appendString(szText,"					<YieldChanges>")
					for iJ in range(YieldTypes.NUM_YIELD_TYPES):
						szText = appendString(szText,"					<iYieldChange>%s</iYieldChange>" %(objImprovementInfo.getImprovementBonusYield(iI,iJ)))
					szText = appendString(szText,"					</YieldChanges>")					
					szText = appendString(szText,"				</BonusTypeStruct>")
			szText = appendString(szText,"			</BonusTypeStructs>")
#		else:
#			szText = appendString(szText,"			<BonusTypeStructs/>")

		if(objImprovementInfo.getImprovementPillage() != -1):
			szText = appendString(szText,"			<ImprovementPillage>%s</ImprovementPillage>" %(gc.getImprovementInfo(objImprovementInfo.getImprovementPillage()).getType()))
		else:
			szText = appendString(szText,"			<ImprovementPillage/>")

		if(objImprovementInfo.getImprovementUpgrade() != -1):
			szText = appendString(szText,"			<ImprovementUpgrade>%s</ImprovementUpgrade>" %(gc.getImprovementInfo(objImprovementInfo.getImprovementUpgrade()).getType()))
		else:
			szText = appendString(szText,"			<ImprovementUpgrade/>")

		if(self.isTechYieldChangesDefined(iImprovement)):
			szText = appendString(szText,"			<TechYieldChanges>")
			for iI in range(gc.getNumTechInfos()):
				if(self.isTechYieldChangeDefined(iImprovement, iI)):
					szText = appendString(szText,"				<TechYieldChange>")
					szText = appendString(szText,"					<PrereqTech>%s</PrereqTech>" %(gc.getTechInfo(iI).getType()))
					szText = appendString(szText,"					<TechYields>")
					for iJ in range(YieldTypes.NUM_YIELD_TYPES):
						szText = appendString(szText,"						<iYield>%s</iYield>" %(objImprovementInfo.getTechYieldChanges(iI,iJ)))
					szText = appendString(szText,"					</TechYields>")					
					szText = appendString(szText,"				</TechYieldChange>")
			szText = appendString(szText,"			</TechYieldChanges>")
		else:
			szText = appendString(szText,"			<TechYieldChanges/>")

		if(self.isRouteYieldChangesDefined(iImprovement)):
			szText = appendString(szText,"			<RouteYieldChanges>")
			for iI in range(gc.getNumRouteInfos()):
				if(self.isRouteYieldChangeDefined(iImprovement, iI)):
					szText = appendString(szText,"				<RouteYieldChange>")
					szText = appendString(szText,"					<RouteType>%s</RouteType>" %(gc.getRouteInfo(iI).getType()))
					szText = appendString(szText,"					<RouteYields>")
					for iJ in range(YieldTypes.NUM_YIELD_TYPES):
						szText = appendString(szText,"						<iYield>%s</iYield>" %(objImprovementInfo.getRouteYieldChanges(iI,iJ)))
					szText = appendString(szText,"					</RouteYields>")					
					szText = appendString(szText,"				</RouteYieldChange>")
			szText = appendString(szText,"			</RouteYieldChanges>")
		else:
			szText = appendString(szText,"			<RouteYieldChanges/>")

		if(len(objImprovementInfo.getWorldSoundscapeScriptString()) > 0):
			szText = appendString(szText,"			<WorldSoundscapeAudioScript>%s</WorldSoundscapeAudioScript>" %(objImprovementInfo.getWorldSoundscapeScriptString()))
#		else:
#			szText = appendString(szText,"			<WorldSoundscapeAudioScript/>")

		szText = appendString(szText,"			<bGraphicalOnly>%s</bGraphicalOnly>" %(boolToInt(objImprovementInfo.isGraphicalOnly())))

		szText = appendString(szText,"		</ImprovementInfo>")
			
		return szText

						
	def printImprovements(self):	
	
		strSavePath = ""
		strFileSavePath = ""
		strModPath = ""
		strModAssetPath = ""
		strModAssetSavePath = ""
		strModAssetPath = ""
		
		if(os.access(CvPath.userActiveModDir,os.F_OK)):
			strModPath = CvPath.userActiveModDir
		elif(os.access(CvPath.installActiveModDir,os.F_OK)):
			strModPath = CvPath.installActiveModDir
		else:
			self.dataSavePopup(false)
			return
			
		strSavePath = "%s\%s" %(strModPath,g_strSaveDirectoryLocation)
		strModAssetPath = "%s\\Assets\\" %(strModPath)
		
		if(g_bCreateAssetHierarchy):
			strSavePath += "\Assets\XML\Terrain" 

		strFileSavePath = "%s\%s" %(strSavePath, "CIV4ImprovementInfos.xml")

		try:
			if(os.access(strSavePath,os.F_OK)):
				if(os.access(strFileSavePath,os.F_OK)):
					os.remove(strFileSavePath)
				os.removedirs(strSavePath)
		except:
			pass
			
		if(not os.access(strSavePath,os.F_OK)):
			os.makedirs(strSavePath)

							
		szText = "<?xml version=\"1.0\"?>"
		szText = appendString(szText,"<!-- Created by Tech Civilizeditor %s by TheLopez-->" %(editorVersion()))
		szText = appendString(szText,"<!-- Sid Meier's Civilization 4 -->")
		szText = appendString(szText,"<!-- Copyright Firaxis Games 2005 -->")
		szText = appendString(szText,"<!-- -->")
		szText = appendString(szText,"<!-- Improvement -->")
		szText = appendString(szText,"<Civ4ImprovementInfos xmlns=\"x-schema:CIV4TerrainSchema.xml\">")
		szText = appendString(szText,"	<ImprovementInfos>")
				
		for iImprovement in range(gc.getNumImprovementInfos()):

			if(gc.getImprovementInfo(iImprovement).isDeleted()):
				continue

			szText = appendString(szText,self.printImprovement(iImprovement))
			
						
		szText = appendString(szText,"	</ImprovementInfos>")
		szText = appendString(szText,"</Civ4ImprovementInfos>")

			
		fd = os.open(strFileSavePath, os.O_CREAT)
		os.close(fd)

		fd = os.open(strFileSavePath, os.O_RDWR)
		os.write(fd, szText)
		os.close(fd)
		
		if(g_bSaveChangesInEditorAssetsDirectory):
			strModAssetPath = "%s\%s" %(strModPath,"\Assets\XML\Terrain")
			strModAssetSavePath = "%s\%s" %(strModPath, "\Assets\XML\Terrain\CIV4ImprovementInfos.xml")
			try:
				if(os.access(strModAssetPath,os.F_OK)):
					if(os.access(strModAssetSavePath,os.F_OK)):
						os.remove(strModAssetSavePath)
			except:
				pass
			
			if(not os.access(strModAssetPath,os.F_OK)):
				os.makedirs(strModAssetPath)

			fd = os.open(strModAssetSavePath, os.O_CREAT)
			os.close(fd)

			fd = os.open(strModAssetSavePath, os.O_RDWR)
			os.write(fd, szText)
			os.close(fd)
	

